#pragma once

// TODO: FREERTOS

#include <stdlib.h>

#ifndef ARDUINO_BASIC__HEAP_USE_FREERTOS
    #if __has_include("FreeRTOS.h")
        #define _ARDUINO__BASIC__HEAP__USE__FREERTOS (1)
    #endif
#endif


#ifdef ARDUINO_BASIC__HEAP_USE_STDLIB
    #ifdef _ARDUINO__BASIC__HEAP__USE__FREERTOS
        #undef _ARDUINO__BASIC__HEAP__USE__FREERTOS
    #endif

    #define _ARDUINO__BASIC__HEAP__USE__FREERTOS(0)
#endif


#if ARDUINO_BASIC__HEAP_USE_FREERTOS > 1

extern "C" {

extern void* pvPortMalloc(size_t xWantedSize);

extern void vPortFree(void* pv);

extern void* pvPortRealloc(void* pv, size_t xWantedSize);

// 如果没有realloc，就在这里提供一个简单的weak 实现，可被覆盖

inline void* pvPortRealloc(void* pv, size_t xWantedSize) {
    vPortFree(pv);
    return pvPortMalloc(xWantedSize);
}
}

#endif


namespace arduino_basic {

#ifdef ARDUINO_BASIC__HEAP_USE_FREERTOS

    inline void* heap_malloc(size_t s) {
        return pvPortMalloc(s);
    }

    inline void heap_free(void* p) {
        vPortFree(p);
    }

    inline void* heap_realloc(void* p, size_t s) {
        return pvPortRealloc(p, s);
    }

#else

    inline void* heap_malloc(size_t s) {
        return malloc(s);
    }

    inline void heap_free(void* p) {
        free(p);
    }

    inline void* heap_realloc(void* p, size_t s) {
        return realloc(p, s);
    }

#endif

}  // namespace arduino_basic